import styles from "./login.module.scss";
import type { FormProps } from "antd";
import { Button, Checkbox, Form, Input, Col, Row } from "antd";
import { useNavigate } from "react-router-dom";
import { useState } from "react";

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

export default function Login() {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [login, setLogin] = useState(false);
  const onReset = () => {
    form.resetFields();
  };
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    localStorage.setItem(
      "token",
      JSON.stringify({
        username: values.username!,
        password: values.password!,
      })
    );
    // 跳转首页
    navigate("/home", { replace: true });
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div className={styles.container}>
      <div className={styles.loginBox}>
        <div className={styles.leftSection}>
          {`欢迎${login ? "回" : "来"}到琪琪音乐！`}
          <Button type="text" onClick={() => setLogin(!login)}>
            {login ? "登录" : "注册"}
          </Button>
        </div>
        <div className={styles.rightSection}>
          <div className={styles.title}>{login ? "注册" : "登录"}</div>
          <Form
            name="basic"
            className={styles.formBox}
            layout="vertical"
            form={form}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="账号"
              name="username"
              rules={[{ required: true, message: "请输入账号" }]}
            >
              <Input placeholder="请输入账号" />
            </Form.Item>

            <Form.Item<FieldType>
              label="密码"
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>

            <Form.Item<FieldType>
              name="remember"
              valuePropName="checked"
              label={null}
            >
              <Checkbox>记住密码</Checkbox>
            </Form.Item>

            <Form.Item>
              <Row gutter={16}>
                <Col span={18}>
                  <Button block type="primary" htmlType="submit">
                    登录
                  </Button>
                </Col>
                <Col span={6}>
                  <Button block htmlType="button" onClick={onReset}>
                    重置
                  </Button>
                </Col>
              </Row>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
}
